package zhieasy.cn.xpu_helper.security.filter;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.filter.OncePerRequestFilter;
import zhieasy.cn.xpu_helper.security.exception.WechatCodeException;
import zhieasy.cn.xpu_helper.security.exception.WechatCodeNullException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author DaHang
 * @date 2020/8/14 16:42
 */
@Component
public class ValidateWechatCodeFilter extends OncePerRequestFilter {

    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest,
                                    HttpServletResponse httpServletResponse,
                                    FilterChain filterChain)
        throws ServletException, IOException {


        if(StringUtils.equals("/common/wechat/login", httpServletRequest.getRequestURI())
            && StringUtils.equalsIgnoreCase(httpServletRequest.getMethod(), "post"  )){
            try {
                validateWechatCode(httpServletRequest);
            }catch (WechatCodeException e) {
                authenticationFailureHandler.onAuthenticationFailure(httpServletRequest,httpServletResponse,e);
                return;
            }
        }

        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }

    //校验code是否正确
    private void validateWechatCode(HttpServletRequest request) throws ServletRequestBindingException {
        //请求里的手机号和验证码
        String wechatCode = request.getParameter("wechatCode");
        System.out.println(wechatCode);
        //ValidateCode codeInSession = (ValidateCode) session.getAttribute(mobileInRequest);

        if (StringUtils.isBlank(wechatCode)) {
            throw new WechatCodeNullException("code不能为空");
        }

    }

    public AuthenticationFailureHandler getAuthenticationFailureHandler() {
        return authenticationFailureHandler;
    }

    public void setAuthenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) {
        this.authenticationFailureHandler = authenticationFailureHandler;
    }

}
